/*
 * @Description:想定库
 * @Author: ldx
 * @Date: 2022-09-18 22:35:41
 * @LastEditors: ldx
 * @LastEditTime: 2022-09-29 23:32:42
 */
import { DownOutlined, UploadOutlined } from '@ant-design/icons'
import { useAntdTable, useRequest } from 'ahooks'
import {
  Button,
  Col,
  div,
  Dropdown,
  Form,
  Image,
  Input,
  Menu,
  message,
  Modal,
  Popconfirm,
  Row,
  Table,
  Upload
} from 'antd'
const { TextArea } = Input
import moment from 'moment'
import { useState } from 'react'

import {
  createScenarioLibrary,
  deleteScenarioLibrary,
  downloadScenarioLibrary,
  queryDetails,
  queryScenarioLibrary,
  syncWorkScenarioLibrary,
  updateScenarioLibrary
} from '@/api/scenario'
import { TextTooltip } from '@/components'
import AuthButton from '@/components/authButton'
import { PageContainer } from '@/components/pageContainer'
const ScenarioLibrary = () => {
  const [form] = Form.useForm()
  const [addForm] = Form.useForm()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isModalOpenDetails, setIsModalOpenDetails] = useState(false)
  const [isModalOpenSnapshot, setIsModalOpenSnapshot] = useState(false)
  const [details, setDetails] = useState<any>()
  /** 想定库列表 */
  const { tableProps, search } = useAntdTable(queryScenarioLibrary, {
    form
  })

  /** 想定库详情 */
  const { runAsync: runQueryDetails } = useRequest(queryDetails, {
    manual: true,
    onSuccess: (res) => {
      setDetails(res.data)
    }
  })
  /** 想定库删除 */
  const { runAsync: runDeleteScenarioLibrary } = useRequest(
    deleteScenarioLibrary,
    {
      manual: true,
      onSuccess: () => {
        search.submit()
      }
    }
  )
  /** 想定库下载 */
  const { runAsync: runDownloadScenarioLibrary } = useRequest(
    downloadScenarioLibrary,
    {
      manual: true,
      onSuccess: (res) => {
        const filename = res.headers['content-disposition']
          .split(';')[1]
          .split('=')[1]
        // 创建隐藏的可下载链接
        const eleLink = document.createElement('a')
        eleLink.download = decodeURIComponent(filename)
        eleLink.style.display = 'none'
        // 字符内容转变成blob地址
        const blob = new Blob([res.data])
        eleLink.href = URL.createObjectURL(blob)
        // 触发点击
        document.body.appendChild(eleLink)
        eleLink.click()
        // 然后移除
        document.body.removeChild(eleLink)
      }
    }
  )
  /** 创建想定库 */
  const { runAsync: runCreateScenarioLibrary } = useRequest(
    createScenarioLibrary,
    {
      manual: true,
      onSuccess: () => {
        search.reset()
        setIsModalOpen(false)
        addForm.resetFields()
        message.success('创建成功')
        setDetails(undefined)
      }
    }
  )
  /** 更新想定库 */
  const { runAsync: runUpdateScenarioLibrary } = useRequest(
    updateScenarioLibrary,
    {
      manual: true,
      onSuccess: () => {
        search.reset()
        setIsModalOpen(false)
        addForm.resetFields()
        message.success('更新成功')
        setDetails(undefined)
      }
    }
  )
  /** 同步想定库 */
  const { runAsync: runSyncWorkScenarioLibrary } = useRequest(
    syncWorkScenarioLibrary,
    {
      manual: true,
      onSuccess: () => {
        search.submit()
        message.success('同步成功')
      }
    }
  )
  const columns: any[] = [
    {
      title: '序号',
      width: 60,
      align: 'center',
      dataIndex: 'a',
      render: (text: string, record: any, index: number) => {
        return <span>{index + 1}</span>
      }
    },
    {
      title: '想定名称',
      align: 'center',
      dataIndex: 'scenarioName'
    },
    {
      title: '摘要',
      align: 'center',
      ellipsis: true,
      dataIndex: 'description'
    },
    {
      title: '同步作业',
      align: 'center',
      dataIndex: 'syncWork',
      render: (text: number) => {
        return <span>{text === 0 ? '未同步' : '已同步'}</span>
      }
    },
    {
      title: '文件名称',
      align: 'center',
      ellipsis: true,
      dataIndex: 'fileName'
    },
    {
      title: '文件路径',
      align: 'center',
      ellipsis: true,
      dataIndex: 'filePath'
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      render: (text: string) => {
        return <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
      }
    },
    {
      title: '创建人',
      align: 'center',
      dataIndex: 'creatorName'
    },
    {
      title: '操作',
      width: 300,
      align: 'center',
      key: 'action',
      render: (text: number, record: any) => (
        <div>
          <AuthButton
            auth={[
              '/**',
              '/scenario-library/**',
              '/scenario-library/details/{id}'
            ]}
            type="link"
            onClick={() => {
              setIsModalOpenDetails(true)
              runQueryDetails(record.id)
            }}
          >
            详情
          </AuthButton>
          <Popconfirm
            title="确认下载?"
            onConfirm={() => runDownloadScenarioLibrary(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <AuthButton
              auth={[
                '/**',
                '/scenario-library/**',
                '/scenario-library/download/{id}'
              ]}
              type="link"
            >
              下载
            </AuthButton>
          </Popconfirm>
          <AuthButton
            type="link"
            auth={['/**', '/equip/**', '/scenario-library/update']}
            onClick={() => {
              // setRole(record)
              runQueryDetails(record.id).then(() => {
                addForm.setFieldsValue(record)
                setIsModalOpen(true)
                // setDetails(record)
              })
            }}
          >
            编辑
          </AuthButton>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item key="2">
                  <AuthButton
                    auth={[
                      '/**',
                      '/scenario-library/**',
                      '/scenario-library/sync-work/{id}'
                    ]}
                    onClick={() => runSyncWorkScenarioLibrary(record.id)}
                    type="link"
                  >
                    同步
                  </AuthButton>
                </Menu.Item>
                <Menu.Item key="3">
                  <AuthButton
                    auth={['/**', '/scenario-library/**']}
                    onClick={() => {
                      setIsModalOpenSnapshot(true)
                      setDetails(record)
                    }}
                    type="link"
                  >
                    快照
                  </AuthButton>
                </Menu.Item>
                <Menu.Item key="1">
                  <Popconfirm
                    title="确认删除想定?"
                    onConfirm={() => runDeleteScenarioLibrary(record.id)}
                    okText="是"
                    cancelText="否"
                  >
                    <AuthButton
                      auth={[
                        '/**',
                        '/scenario-library/**',
                        '/scenario-library/delete/{id}'
                      ]}
                      type="link"
                    >
                      删除
                    </AuthButton>
                  </Popconfirm>
                </Menu.Item>
              </Menu>
            }
          >
            <Button type="link">
              {' '}
              更多
              <DownOutlined />
            </Button>
          </Dropdown>
        </div>
      )
    }
  ]
  return (
    <>
      <PageContainer>
        <div>
          <Form form={form}>
            <Row gutter={24}>
              <Col span={5}>
                <Form.Item name="keyword">
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Button onClick={() => search.submit()} type="primary">
                  搜索
                </Button>
              </Col>
              <Col span={11} className="flex justify-end">
                <AuthButton
                  auth={[
                    '/**',
                    '/scenario-library/**',
                    '/scenario-library/create'
                  ]}
                  onClick={() => setIsModalOpen(true)}
                  type="primary"
                >
                  创建
                </AuthButton>
              </Col>
            </Row>
          </Form>
          <Table
            columns={columns}
            scroll={{ x: 1400 }}
            rowKey={(record) => record.id}
            {...tableProps}
            pagination={{
              showTotal: (total, range) => {
                console.log('xxx', range)
                const num = Math.ceil(total / 10)
                return (
                  <span style={{ color: '#fff', marginRight: '10px' }}>
                    共{num}页/共{total}条结果
                  </span>
                )
              },
              ...tableProps.pagination
            }}
          />
        </div>
      </PageContainer>
      <Modal
        width={800}
        title="想定详情"
        visible={isModalOpenDetails}
        onOk={() => {
          setIsModalOpenDetails(false)
          setDetails(undefined)
        }}
        onCancel={() => {
          setIsModalOpenDetails(false)
          setDetails(undefined)
        }}
      >
        <div className="pl-20px details">
          <div className="">
            <span className="w-120px inline-block"></span>
            <span className="520px flex justify-center">
              <img
                style={{ width: '160px', height: '160px' }}
                src={`${window.location.origin}${details?.imgUri}`}
                alt=""
              />
            </span>
          </div>
          <div className="">
            <span className="w-120px inline-block">想定名称：</span>
            <span>{details?.scenarioName}</span>
          </div>
          <div className="">
            <span className="w-120px inline-block">摘要：</span>
            <span>
              <TextTooltip className="w-520px">
                {details?.description}
              </TextTooltip>{' '}
            </span>
          </div>
          <div className="">
            <span className="w-120px inline-block">文件名称：</span>
            <span>
              <TextTooltip className="w-520px">{details?.fileName}</TextTooltip>{' '}
            </span>
          </div>
          <div className="">
            <span className="w-120px inline-block">文件路径：</span>
            <span>
              <TextTooltip className="w-520px">{details?.filePath}</TextTooltip>
            </span>
          </div>
          <div className="">
            <span className="w-120px inline-block">设备快照名称：</span>
            <span>
              <TextTooltip className="w-520px">{details?.imgName}</TextTooltip>{' '}
            </span>
          </div>
          <div className="">
            <span className="w-120px inline-block">设备快照路径：</span>
            <span>
              <TextTooltip className="w-520px">{details?.imgPath}</TextTooltip>
            </span>
          </div>

          <div className="">
            <span className="w-120px inline-block">创建时间：</span>
            <span>
              {moment(details?.createTime).format('YYYY-MM-DD HH:mm:ss')}
            </span>
          </div>
          <div className="">
            <span className="w-120px inline-block">创建人：</span>
            <span>{details?.creatorName}</span>
          </div>
          <div className="">
            <span className="w-120px inline-block">更新时间：</span>
            <span>
              {details?.updateTime
                ? moment(details?.updateTime).format('YYYY-MM-DD HH:mm:ss')
                : ''}
            </span>
          </div>
          <div className="">
            <span className="w-120px inline-block">更新人：</span>
            <span>{details?.updateName}</span>
          </div>
        </div>
      </Modal>
      <Modal
        width={800}
        title={details ? '编辑想定库' : '上传想定库'}
        visible={isModalOpen}
        onOk={() => {
          if (details) {
            addForm.validateFields().then((values) => {
              runUpdateScenarioLibrary({
                ...details,
                ...values
              })
            })
          } else {
            addForm.validateFields().then((values) => {
              const formData = new FormData()
              formData.append('scenarioFile', values.scenarioFile.file)
              formData.append('scenarioImg', values.scenarioImg.file)
              formData.append('scenarioName', values.scenarioName)
              formData.append('description', values.description)
              runCreateScenarioLibrary(formData)
            })
          }
        }}
        onCancel={() => {
          setIsModalOpen(false)
          addForm.resetFields()
          setDetails(undefined)
        }}
      >
        <div>
          <Form
            name="register"
            initialValues={{
              prefix: '86'
            }}
            form={addForm}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item
              name="scenarioName"
              label="想定名称"
              rules={[{ required: true, message: '请输入想定名称' }]}
            >
              <Input></Input>
            </Form.Item>
            <Form.Item
              name="description"
              label="摘要"
              rules={[{ required: true, message: '请输入摘要' }]}
            >
              <TextArea rows={4}></TextArea>
            </Form.Item>
            {!details && (
              <>
                <Form.Item
                  name="scenarioFile"
                  label="文件"
                  rules={[{ required: true, message: '请上传文件' }]}
                >
                  <Upload
                    className="basis-upload"
                    beforeUpload={() => false}
                    accept=".xml,.zip,.rar,.7z,.tar"
                    headers={{
                      authorization: 'authorization-text'
                    }}
                  >
                    <Button icon={<UploadOutlined />}>上传</Button>
                  </Upload>
                </Form.Item>
                <Form.Item
                  name="scenarioImg"
                  label="图片"
                  rules={[{ required: true, message: '请上传图片' }]}
                >
                  <Upload
                    className="basis-upload"
                    beforeUpload={() => false}
                    accept=".jpg,.png,.gif,.jpeg"
                    headers={{
                      authorization: 'authorization-text'
                    }}
                  >
                    <Button icon={<UploadOutlined />}>上传</Button>
                  </Upload>
                </Form.Item>
              </>
            )}
          </Form>
        </div>
      </Modal>
      <Modal
        width={800}
        title="快照"
        visible={isModalOpenSnapshot}
        onCancel={() => setIsModalOpenSnapshot(false)}
        footer={null}
        width={916}
      >
        <Image
          width={870}
          src={`${window.location.origin}${details?.imgUri}`}
          fallback=""
        />
      </Modal>
    </>
  )
}

export default ScenarioLibrary
